package com.zzyl.intercept;

import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Value("${zzyl.framework.jwt.base64-encoded-secret-key}")
    private String base64EncodedSecretKey;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if(token == null || token == ""){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        try {
            Claims claims = JwtUtil.parseJWT(base64EncodedSecretKey, token);
            if(claims == null || claims.isEmpty()){
                throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
            }
//            Integer id = (Integer) claims.get("id");
//            UserThreadLocal.set(Long.parseLong(id.toString()));
            Integer id = (Integer) claims.get("id");
            int intId=id;
            UserThreadLocal.set(Long.valueOf(intId));
        } catch (Exception e) {
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
